package cn.lsnu.heritage.controller;

import cn.lsnu.heritage.common.Result;
import cn.lsnu.heritage.model.doc.HeritageDoc;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("kGraph")
@RequiredArgsConstructor
public class KnowledgeGraphController {

    private final ElasticsearchClient client;


    @SneakyThrows
    @GetMapping
    public Result<List<HeritageDoc>> geoDistance(Double lat, Double lon,Double distance,Integer categoryId){
        SearchResponse<HeritageDoc> response = null;
        if (categoryId == 0){
            // 查询附近全部分类
            response = client.search(s -> s
                            .index("heritages")
                            .query(q -> q.geoDistance(geo -> geo
                                    .field("location")
                                    .distance(distance + "km")
                                    .location(l -> l
                                            .latlon(lo -> lo.lat(lat).lon(lon)))))
                            .size(3610)
                    , HeritageDoc.class);
        }else{
            // 查询附近分类
            response = client.search(s -> s.index("heritages")
                            .query(q -> q.bool(b -> b
                                            .must(m -> m.term(t -> t.field("categoryId").value(categoryId)))
                                            .filter(f -> f.geoDistance(geo -> geo.field("location")
                                                            .distance(distance + "km")
                                                            .location(l -> l
                                                                    .latlon(lo -> lo.lat(lat).lon(lon)))))))
                            .size(3610)
                    , HeritageDoc.class);
        }

        List<Hit<HeritageDoc>> hitList = response.hits().hits();
        List<HeritageDoc> heritageDocList = new ArrayList<>();
        for (Hit<HeritageDoc> hit : hitList) {
            heritageDocList.add(hit.source());
        }
        return Result.success(heritageDocList);
    }
}
